package org.zezi.loader.ui.fragment;

import org.zezi.loader.R;
import org.zezi.loader.provider.ShopListContract.Items;
import org.zezi.loader.ui.adapter.ItemsCursorAdapter;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class LoaderFragment extends ListFragment implements LoaderCallbacks<Cursor>, OnQueryTextListener {

	public static final String TAG = "LoaderFragment";

	public static final int LOADER_TEST = 0;

	static final String[] ITEMS_PROJECTION = new String[] { Items._ID, Items.COLUMN_NAME_NAME,
			Items.COLUMN_NAME_COUNT };

	// This is the Adapter being used to display the list's data.
	// private SimpleCursorAdapter mAdapter;
	private ItemsCursorAdapter mAdapter;

	// If non-null, this is the current filter the user has provided.
	private String mCurFilter;

	private LoaderTaskFragment mWorkFragment;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_loader, container, false);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		FragmentManager fm = getFragmentManager();

		mWorkFragment = (LoaderTaskFragment) fm.findFragmentByTag(LoaderTaskFragment.TAG);

		if (mWorkFragment == null) {
			mWorkFragment = new LoaderTaskFragment();
			// Tell it who it is working with.
			mWorkFragment.setTargetFragment(this, 0);
			fm.beginTransaction().add(mWorkFragment, LoaderTaskFragment.TAG).commit();
		}

		// We have a menu item to show in action bar.
		setHasOptionsMenu(true);

		// Create an empty adapter we will use to display the loaded data.
		mAdapter = new ItemsCursorAdapter(getActivity(), null, 0);
		// mAdapter = new SimpleCursorAdapter(
		// getActivity(),
		// android.R.layout.simple_list_item_2,
		// null,
		// new String[] { Items.COLUMN_NAME_NAME, Items.COLUMN_NAME_COUNT },
		// new int[] {android.R.id.text1, android.R.id.text2 },
		// 0);

		setListAdapter(mAdapter);

		// Prepare the loader. Either re-connect with an existing one,
		// or start a new one.
		getLoaderManager().initLoader(LOADER_TEST, null, this);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_fragment_loader, menu);
		SearchView sv = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		sv.setOnQueryTextListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menu_search: {
			// Do nothing..
			return true;
		}
		case R.id.menu_delete: {
			getActivity().getContentResolver().delete(Items.CONTENT_URI, null, null);
			return true;
		}
		default: {
			return false;
		}
		}
	}

	public boolean onQueryTextChange(String newText) {
		// Called when the action bar search text has changed. Update
		// the search filter, and restart the loader to do a new query
		// with this filter.
		mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
		getLoaderManager().restartLoader(0, null, this);
		return true;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		return true;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// Insert desired behavior here.
		Log.i("FragmentComplexList", "Item clicked: " + id);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		Log.i(TAG, "@@ onCreateLoader");
		Uri baseUri;
		if (mCurFilter != null) {
			baseUri = Uri.withAppendedPath(Items.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
		} else {
			baseUri = Items.CONTENT_URI;
		}

		return new CursorLoader(getActivity(), baseUri, ITEMS_PROJECTION, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
		Log.i(TAG, "@@ onLoadFinished");
		// Swap the new cursor in. (The framework will take care of closing the
		// old cursor once we return.)
		mAdapter.swapCursor(data);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		Log.i(TAG, "@@ onLoaderReset");
		// This is called when the last Cursor provided to onLoadFinished()
		// above is about to be closed. We need to make sure we are no
		// longer using it.
		mAdapter.swapCursor(null);
	}

}
